import { createRouter, createWebHistory } from "vue-router";
import { userInfo } from "@/stores/userinfo";
import allUserApi from "@/api/Backend/AllUserApi";

import ContestStart from "../components/front/contest/ContestStart.vue";
import ContestWait from "@/components/front/contest/ContestWait.vue";
import HomeView from "../views/HomeView.vue";
import ContestList from "../components/front/contest/ContestList.vue";
import ContestFrame from "../components/front/contest/ContestFrame.vue";
import ContestView from "@/components/front/contest/ContestOn.vue";
import BackendView from "@/views/BackendView.vue";
import LoginView from "@/views/auth/LoginView.vue";
import RegisterView from "@/views/auth/RegisterView.vue";
import MainFrame from "@/views/MainFrame.vue";
import UserCenter from "../views/UserCenter.vue";
import VaTaskFrame from "@/components/front/vatask/VaTaskFrame.vue";
import RangeFrame from "@/components/front/range/RangeFrame.vue";
// 导入新创建的AI评价组件
import AiEvaluation from "@/components/front/vatask/AiEvaluation.vue";
import MyVulnerability from "@/components/front/vatask/MyVulnerability.vue";
import BackHome from "@/components/BackHome.vue";
import ContestEnd from "../components/front/contest/ContestEnd.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "用户界面",
      component: MainFrame,
      children: [
        {
          path: "/",
          name: "首页",
          component: HomeView,
        },
        // 顶部导航考试路由
        {
          path: "/range",
          name: "靶场模块",
          component: RangeFrame,
        },
        {
          path: "/contest",
          name: "考试模块",
          component: ContestFrame,
          redirect: "/contest/list",
          children: [
            {
              path: "/contest/list",
              name: "我的考试",
              component: ContestList,
            },
            {
              path: "/contest/ongoing",
              name: "进行中的考试",
              component: ContestView,
              redirect: "/contest/wait",
              children: [
                {
                  path: "/contest/wait",
                  name: "等待大厅",
                  component: ContestWait,
                },
                {
                  path: "/contest/start",
                  name: "考试界面",
                  component: ContestStart,
                },
              ],
            },
            {
              path: "/contest/end",
              name: "结束界面",
              component: ContestEnd,
            },
          ],
        },
        {
          path: "/vatask",
          name: "漏洞分析任务",
          component: VaTaskFrame,
          redirect: "/vatask/myVulnerability", // 添加默认重定向
          children: [
            {
              path: "/vatask/myVulnerability", // 使用相对路径
              name: "我的漏洞",
              component: MyVulnerability, // 新添加的组件路由
            },
            {
              path: "/vatask/AiEvaluation",
              name: "AI评价",
              component: AiEvaluation,
            },
          ],
        },
        {
          path: "/personal",
          name: "个人中心",
          component: UserCenter,
        },
      ],
    },
    // 后台管理端， 暂时放在顶部导航联系我们中
    {
      path: "/login",
      name: "登录界面",
      component: LoginView,
    },
    {
      path: "/register",
      name: "注册界面",
      component: RegisterView,
    },
    {
      path: "/backend",
      name: "后台管理",
      component: BackendView,
      redirect: "/backend/index",
      children: [
        {
          path: "/backend/index",
          name: "后台首页",
          component: BackHome,
        },
      ],
    },
  ],
});

//递归生成动态路由
/**
 * 生成单个路由对象
 * @param menu 菜单项数据
 * @returns 单个路由对象
 */
function generateSingleRoute(menu: any) {
  return {
    path: menu.menuHref,
    name: menu.menuTitle,
    component: () => import(`@/components/${menu.menuCurl}.vue`), // 假设组件路径是基于菜单配置的
    children: [],
  };
}

/**
 * 递归生成动态路由
 * @param menuList 菜单列表数据
 * @returns 动态生成的路由数组
 */
function generateDynamicRoutes(menuList: any[]) {
  const routes = [];
  for (const menu of menuList) {
    const route = generateSingleRoute(menu);
    if (menu.subMenu && menu.subMenu.length > 0) {
      route.children = generateDynamicRoutes(menu.subMenu); // 递归处理子菜单
    }
    router.addRoute("后台管理", route);
    routes.push(route);
  }
  return routes;
}

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = userInfo();
  //加载动态路由
  if (userStore.menuList.length === 0) {
    if (userStore.userInfo.userId == "3") {
      next();
    } else {
      allUserApi.getRoute({ userId: userStore.userInfo.userId }).then((res) => {
        if (res.code === 200) {
          generateDynamicRoutes(res.data);
        } else {
          console.log("路由获取失败,请尝试重新登录");
          next({ path: "/login" });
        }
      });
    }
  }
  //默认放行的页面
  if (
    to.path === "/login" ||
    to.path === "/register" ||
    to.path === "/" ||
    to.path === "/index"
  ) {
    next();
    //backend检查用户权限
  } else if (to.path.startsWith("/backend")) {
    if (userStore.getRole < 3) {
      next();
    } else {
      ElMessage.error("权限不足");
      // 重定向到首页或其他页面
      next({ path: "/" });
    }
    //登录后放行后台以外的页面
  } else if (userStore.userInfo.userId) {
    next();
    //未登录则要求登录
  } else {
    ElMessage.error("先登录后再使用哦");
    next({ path: "/login" });
  }
});

export default router;
